import store from '@/store'

/**
 * 权限判断
 * @param {*} param0 菜单或者按钮是否拥有该权限
 */
const setPermission = ({ role, el }) => {
    const userInfo = store.getters && store.getters['user/userInfo'] && store.getters['user/userInfo']
    const { roles } = userInfo
    let tipsText = !el ? '$permission(["admin", "editor"])' : `v-permission="['admin','editor']"`
    if (role && role instanceof Array && role.length > 0) {
        const permissionRoles = role
        let hasPermission = true
        if (roles !== null && roles.length) {
            hasPermission = roles.some(role => {
                return permissionRoles.includes(role)
            })
            if (el && !hasPermission) {
                el.parentNode && el.parentNode.removeChild(el)
            } else {
                return hasPermission
            }
        } else {
            if (el) {
                el.parentNode && el.parentNode.removeChild(el)
            } else {
                return false
            }
        }
    } else {
        throw new Error(`need roles! Like ${tipsText}`)
    }
}
// 权限函数

export const permission = (role) => {
    return setPermission({ role })
}
// 权限指令
export default {
    inserted (el, binding, vnode) {
        const { value } = binding
        setPermission({ role: value, el })
    }
}
